package com.example.ayniu.treadmill.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.ayniu.treadmill.R;
import com.example.ayniu.treadmill.SetPhoneActivity;
import com.example.ayniu.treadmill.base.BaseActivity;
import com.example.ayniu.treadmill.base.MyJsonObjectRequest;
import com.example.ayniu.treadmill.util.UserInfoUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

/**
 * 初始微信登录Acitvity，处理授权结果，获取code以获取用户信息
 * Created by Ayniu on 2016/8/16.
 */
public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {

    public static final String APP_ID = "wxec953b12f6670e4a";
    public static final String APP_SECRET = "e38d35ad986988b5791d1c4f30581485"; //待加密
    private static final String WEIXIN_SCOPE = "snsapi_userinfo";   // 用于请求用户信息的作用域
    private static final String WEIXIN_STATE = "login_state";       // 自定义

    public static RequestQueue mQueue;

    private IWXAPI api;
    private SendAuth.Req req;

    public static String app_code;//全局量，code
    public static String APP_ACCESS_TOKEN;
    public static String APP_EXPIRES_IN;
    public static String APP_REFRESH_TOKEN;
    public static String APP_OPENID;
    public static String APP_SCOPE;
    public static String APP_UNIONID;

    public static String USER_OPENID;   //微信用户openId
    public static String USER_NICKNAME; //微信用户昵称
    public static String USER_CITY;
    public static String USER_UNIONID;

    Button bt_wechatlogin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //注册API
        api = WXAPIFactory.createWXAPI(this, APP_ID);
        api.handleIntent(getIntent(), this);

        initView();

        mQueue = Volley.newRequestQueue(this);//初始化http请求队列对象
//!!!
        //testlogin();    //(待删除)临时测试用,因APP_SECRET可能修改，无法获取正确的微信数据
        initWXLogin();//注册微信实现初始化
    }

    public void initView(){
        bt_wechatlogin = (Button)findViewById(R.id.bt_wechatlogin);
        bt_wechatlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bt_wechatlogin.setBackgroundResource(R.color.main_btbg);
                bt_wechatlogin.setText("启动微信授权中...");
                loginToWechat();
                /*Intent intent = new Intent(WXEntryActivity.this, MainActivity.class);
                startActivity(intent);*/
            }
        });
    }

    //初始化微信登录程序
    private void initWXLogin(){
        //api注册
        api = WXAPIFactory.createWXAPI(this,APP_ID, true);
        api.registerApp(APP_ID);
        // 检查是否安装微信客户端
        if (!api.isWXAppInstalled()) {
            Toast.makeText(this, "未安装微信客户端，请先下载", Toast.LENGTH_LONG);
            return;
        }
    }

    //(待删除)临时测试用,因APP_SECRET可能修改，无法获取正确的微信数据05.04
    public void testlogin(){
        Intent intent = new Intent();
        intent.setClass(WXEntryActivity.this, SetPhoneActivity.class);
        startActivity(intent);
        bt_wechatlogin.setTag("dd");
        finish();
    }

    public void loginToWechat(){
        //授权登录接入
        req = new SendAuth.Req();
        //授权读取用户信息
        req.scope = WEIXIN_SCOPE;
        req.state = WEIXIN_STATE;
        api.sendReq(req);
        //将在次启动，所以先关闭当前Activity
        finish();
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }
    //  发送到微信请求的响应结果
    @Override
    public void onResp(BaseResp resp) {
        if(resp instanceof SendAuth.Resp){
            SendAuth.Resp newResp = (SendAuth.Resp) resp;
            //获取微信传回的code
            app_code = newResp.code;
            getUnionID(app_code);
        }

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                //发送成功
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                bt_wechatlogin.setBackgroundResource(R.drawable.bt_wechatlogin);
                bt_wechatlogin.setText("");
                showToast("用户取消授权");
                //发送取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                bt_wechatlogin.setBackgroundResource(R.drawable.bt_wechatlogin);
                bt_wechatlogin.setText("");
                showToast("用户拒绝授权");
                //发送被拒绝
                break;
            default:
                bt_wechatlogin.setBackgroundResource(R.drawable.bt_wechatlogin);
                bt_wechatlogin.setText("");
                showToast("无法授权");
                //发送返回
                break;
        }
    }

    /*通过code获取用户信息*/
    public void getUnionID(String APP_CODE){
    String get_url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                +"appid=" + APP_ID
                +"&secret=" + APP_SECRET
                +"&code="+APP_CODE
                +"&grant_type=authorization_code";
        Log.i("getUnionID", get_url);
        JsonObjectRequest joRequest_UserInfo = new JsonObjectRequest(get_url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if(response != null) {

                        APP_ACCESS_TOKEN = response.getString("access_token");
                        APP_EXPIRES_IN = response.getString("expires_in");
                        APP_REFRESH_TOKEN = response.getString("refresh_token");
                        APP_OPENID = response.getString("openid");
                        APP_SCOPE = response.getString("scope");
                        APP_UNIONID = response.getString("unionid");
                        getUserInfo(APP_ACCESS_TOKEN, APP_OPENID);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("网络获取失败，请检查网络");
                    Log.e("JSONException", e.getMessage(), e);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                showToast("网络不可用，请检查网络");
                Log.e("onErrorResponse", error.getMessage().toString());
            }
        });
        mQueue.add(joRequest_UserInfo);
    }

    /*通过access_token、openid获取用户信息*/
    public void getUserInfo(String ACCESS_TOKEN, String OPENID){
        String getUser_url = "https://api.weixin.qq.com/sns/userinfo?"
                +"access_token=" + ACCESS_TOKEN
                +"&openid=" + OPENID;
        Log.i("getUserInfo", getUser_url);
        MyJsonObjectRequest joRequest_UserInfo = new MyJsonObjectRequest(getUser_url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if(response != null) {
                        USER_OPENID = response.getString("openid");
                        USER_NICKNAME = response.getString("nickname");
                        USER_UNIONID = response.getString("unionid");
                        //将openId保存到本地，下次使用app获取本地信息即可
                        UserInfoUtil.setLocalPara("USER_OPENID", USER_OPENID);
                        Intent intent = new Intent();
                        intent.setClass(WXEntryActivity.this, SetPhoneActivity.class);
                        startActivity(intent);
                        bt_wechatlogin.setTag("dd");
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("网络不可用，请检查网络");
                    Log.e("JSONException", e.getMessage(), e);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                showToast("网络不可用，请检查网络");
            }
        });
        mQueue.add(joRequest_UserInfo);
    }

    public void showToast(String str){
        Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
    }
}